﻿#include "exportgifdialog.h"
#include "ui_exportgifdialog.h"

#include <QColorDialog>
#include <QFileDialog>
ExportGifDialog::ExportGifDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ExportGifDialog)
{
    ui->setupUi(this);
    this->setWindowFlag(Qt::WindowContextHelpButtonHint, false);
    m_dlgColor = new QColorDialog;
    m_dlgColor->setCurrentColor(m_exportBgColor);
    m_dlgColor->setOption(QColorDialog::NoButtons);
    ui->verticalLayout_color->addWidget(m_dlgColor);
    setDefautlSize(QSize(100, 100));
}

ExportGifDialog::~ExportGifDialog()
{
    delete ui;
}

void ExportGifDialog::setDefautlSize(const QSize &size)
{
    m_defaultSize = size;
    ui->spinBox_w->blockSignals(true);
    ui->spinBox_w->setValue(size.width());
    ui->spinBox_w->blockSignals(false);
    ui->spinBox_h->blockSignals(true);
    ui->spinBox_h->setValue(size.height());
    ui->spinBox_h->blockSignals(false);
    m_exportSize = m_defaultSize;
    m_scaleWH = (double)size.width() / size.height();
}

void ExportGifDialog::on_checkBox_keep_scale_stateChanged(int state)
{
    if(state != Qt::Checked)
        return;
    //计算比例
    int w = ui->spinBox_w->value();
    int h = ui->spinBox_h->value();
    m_scaleWH = (double)w / h;
}

void ExportGifDialog::on_spinBox_w_valueChanged(int w)
{
    if(ui->checkBox_keep_scale->checkState() != Qt::Checked)
        return;
    int h = (int)(w / m_scaleWH);
    ui->spinBox_h->blockSignals(true);
    ui->spinBox_h->setValue(h);
    ui->spinBox_h->blockSignals(false);
}

void ExportGifDialog::on_spinBox_h_valueChanged(int h)
{
    if(ui->checkBox_keep_scale->checkState() != Qt::Checked)
        return;
    int w = (int)(m_scaleWH * h);
    ui->spinBox_w->blockSignals(true);
    ui->spinBox_w->setValue(w);
    ui->spinBox_w->blockSignals(false);
}

void ExportGifDialog::on_pushButton_reset_clicked()
{
    setDefautlSize(m_defaultSize);
}

void ExportGifDialog::on_pushButton_export_clicked()
{
    m_allowAlpha = (ui->checkBox_alpha->checkState() == Qt::Checked);
    m_exportSize.setWidth(ui->spinBox_w->value());
    m_exportSize.setHeight(ui->spinBox_h->value());
    m_exportBgColor = m_dlgColor->currentColor();
    m_exportFile = QFileDialog::getSaveFileName(
        this, u8"保存GIF文件", QString(), u8"动画GIF文件 (*.gif)");
    if(m_exportFile.isEmpty())
        return;
    QFileInfo fileInfo(m_exportFile);
    if(fileInfo.suffix().toLower() != "gif")
        m_exportFile.append(".gif");
    accept();
}
